package com.geek.novel.services

import com.geek.novel.entity.SearchHistory
import com.vicpin.krealmextensions.query
import com.vicpin.krealmextensions.queryFirst
import com.vicpin.krealmextensions.save
import io.realm.Realm
import io.realm.Sort

class SearchHistoryRepository private constructor(){

	/**单例模式*/
	companion object{
		@Volatile
		private var instance: SearchHistoryRepository? = null
		fun getInstance(): SearchHistoryRepository {
			if(instance == null){
				synchronized(SearchHistoryRepository::class.java){
					if(instance == null){
						instance = SearchHistoryRepository()
					}
				}
			}
			return instance!!
		}
	}

	/**保存*/
	fun save(text: String){
		var entity = this.queryByText(text)
		if(entity == null){
			entity = SearchHistory()
			entity.initEntity()
			entity.count = 1
			entity.searchText = text
		}
		entity.searchTime = System.currentTimeMillis()
		entity.save()
	}

	fun queryByText(text: String): SearchHistory? {
		return SearchHistory().queryFirst{ equalTo("searchText", text) }
	}

	/**列出搜索时间倒序的N条数据*/
	fun list(): List<SearchHistory>{
		return SearchHistory().query { sort("searchTime", Sort.DESCENDING).limit(10) }
	}

	/**清空表数据*/
	fun clearData(){
		val realm = Realm.getDefaultInstance()
		//开启事务，然后清空表
		realm.executeTransaction {
			it.delete(SearchHistory::class.java)
		}
	}
	
}